import Vue from 'vue'
import Router from 'vue-router'
import VueRouter from "vue-router";
//引入组件
import Home from '../views/Home'
import ArticleDetail from "../views/ArticleDetail";
import Register from "../views/Register";
import Login from "../views/Login";
import ArticleCreate from "../views/ArticleCreate";
import UserView from "../views/UserView";
import NotFound from "../views/NotFound";
import ManagerLogin from "../views/ManagerLogin";
import QuestionCreate from "../views/QuestionCreate";
import QuestionList from "../views/QuestionList";
import QuestionDetail from "../views/QuestionDetail";
import AnswerList from "../views/AnswerList";


Vue.use(Router)


const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },

    {
      path: '/article/:id',
      name: 'ArticleDetail',
      component: ArticleDetail
    },
    {
      path: '/register',
      name: 'Register',
      component: Register
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/articlecreate',
      name: 'ArticleCreate',
      component: ArticleCreate
    },
    {
      path: '/userview/:username',
      name: 'UserView',
      component: UserView,
    },

    {
      path: '/manager/login',
      name: 'ManagerLogin',
      component: ManagerLogin,
    },
    {
      path: '/manager/questioncreate',
      name: 'QuestionCreate',
      component: QuestionCreate,
    },
    {
      path: '/question',
      name: 'QuestionList',
      component: QuestionList
    },
    {
      path: '/answer/:username',
      name: 'AnswerList',
      component: AnswerList
    },
    {
      path: '/question/:id',
      name: 'QuestionDetail',
      component: QuestionDetail
    },

    {
      path: '*',
      name: '404',
      component: NotFound
    }
  ],

})



router.beforeEach((to, from, next) => {
  if(localStorage.getItem('token') != null) {
    console.log("here" + localStorage.getItem('token'))
    if(to.path === '/login' || to.path === '/register') {
      next('/')
    } else {
      next()
    }
  } else {
    console.log("here" + localStorage.getItem('token'))
    if(to.path === '/login' || to.path === '/register') {
      next()
    }
    else if(to.path === '/manager/login') {
      next()
    } else if(to.path === '/manager/questioncreate') {
      if(localStorage.getItem('mg-token') != null) {
        next()
      } else {
        next('/manager/login?redirect=' + to.fullPath)
      }
    } else {
      next('login?redirect=' + to.fullPath)
    }
  }
})

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
